﻿using BlondeHeaven.DAL;
using BlondeHeaven.DB.Model;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace BlondeHeaven.BLL
{
    /// <summary>
    /// 数据逻辑层：BLL
    /// </summary>
    public class BllUserService<T> : IBllUserService<T> where T : User, new()
    {

        /// <summary>
        /// 数据库服务
        /// </summary>
        protected IDalUserService<T> DBService;

        public BllUserService(IDalUserService<T> dalService)
        {
            this.DBService = dalService;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <param name="IsSave"></param>
        /// <returns></returns>
        public T Add(T model, bool IsSave)
        {
            model = DBService.Add(model);
            if (IsSave)
            {
                if (SaveChanges() > 0)
                    return null;
            }
            return model;
        }

        /// <summary>
        /// 保存数据库
        /// </summary>
        /// <returns></returns>
        public int SaveChanges()
        {
            return DBService.SaveChanges();
        }

        /// <summary>
        /// 用户登入
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="password"></param>
        /// <returns></returns>

        public bool Login(string phone, string password)
        {
            var u = DBService.GetAll().FirstOrDefault(m => m.Phone == phone && m.PassWrod == password);

            if (u != null)
            {
                return true;
            }
            else
            {
                return false;
            }

        }
        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="SiteName"></param>
        /// <param name="imagePath"></param>
        /// <param name="address"></param>
        /// <param name="photo"></param>
        /// <returns></returns>

        public async Task ChangeUserInformation(T model)
        {          
            var user = DBService.GetAll().FirstOrDefault(m => m.Phone == model.Phone);
            user.Name = model.Name;
            user.Phone = model.Phone;
            user.Address = model.Address;
            user.Photo = model.Photo;

            await DBService.EditAsync(user,true);
        }

        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="oldPwg"></param>
        /// <param name="newPwg"></param>
        /// <returns></returns>

        public async Task ChangePassword(string phone, string password)
        {         
            var user = DBService.GetAll().First(m => m.Phone == phone);
            user.PassWrod = password;
            await DBService.EditAsync(user);
        }

    }
}



